<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

// 加载状态
const loading = ref(true);

// 日期范围选择
const dateRange = ref([]);

// 图表实例
let incomeChart = null;
let paymentChart = null;
let trendChart = null;

// 切换图表数据维度
const dataDimension = ref('day');

// 财务统计概览数据
const financeStats = reactive({
    totalIncome: 0,
    totalExpense: 0,
    balance: 0,
    todayIncome: 0,
    yesterdayIncome: 0,
    thisWeekIncome: 0,
    thisMonthIncome: 0,
    comparedYesterday: '+12.5%',
    comparedLastWeek: '+8.3%',
    comparedLastMonth: '+15.2%'
});

// 支付方式统计数据
const paymentStats = ref([]);

// 收入来源数据
const incomeStats = ref([]);

// 订单记录数据
const orderList = ref([]);

// 搜索表单
const searchForm = reactive({
    keyword: '',
    dateRange: [],
    paymentMethod: '',
    orderType: ''
});

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 支付方式选项
const paymentMethodOptions = [
    { label: '微信支付', value: 'wechat' },
    { label: '支付宝', value: 'alipay' },
    { label: '银行卡', value: 'card' },
    { label: '余额支付', value: 'balance' },
    { label: '现金', value: 'cash' }
];

// 订单类型选项
const orderTypeOptions = [
    { label: '房费支付', value: 'room' },
    { label: '会员充值', value: 'recharge' },
    { label: '商品购买', value: 'goods' },
    { label: '团购券', value: 'voucher' }
];

// 计算总收入百分比
const incomePercentage = computed(() => {
    return financeStats.totalIncome > 0
        ? ((financeStats.totalIncome - financeStats.totalExpense) / financeStats.totalIncome * 100).toFixed(1) + '%'
        : '0%';
});

// 加载数据
const loadData = () => {
    loading.value = true;

    // 模拟API请求加载数据
    setTimeout(() => {
        // 模拟统计数据
        financeStats.totalIncome = 185642.56;
        financeStats.totalExpense = 45687.25;
        financeStats.balance = financeStats.totalIncome - financeStats.totalExpense;
        financeStats.todayIncome = 5624.50;
        financeStats.yesterdayIncome = 4987.80;
        financeStats.thisWeekIncome = 32415.70;
        financeStats.thisMonthIncome = 128745.60;

        // 模拟收入来源数据
        incomeStats.value = [
            { value: 35, name: '房费收入' },
            { value: 40, name: '会员充值' },
            { value: 15, name: '商品销售' },
            { value: 10, name: '团购券' }
        ];

        // 模拟支付方式数据
        paymentStats.value = [
            { value: 45, name: '微信支付' },
            { value: 25, name: '支付宝' },
            { value: 15, name: '银行卡' },
            { value: 10, name: '余额支付' },
            { value: 5, name: '现金' }
        ];

        // 模拟订单列表数据
        orderList.value = Array.from({ length: 20 }, (_, index) => {
            const id = 'ORD' + (100000 + index).toString();
            const typeIndex = Math.floor(Math.random() * 4);
            const paymentIndex = Math.floor(Math.random() * 5);
            const now = new Date();
            const orderTime = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);

            // 随机金额
            const amount = (Math.floor(Math.random() * 1000) + 50).toFixed(2);

            // 随机会员信息
            const memberName = `会员${Math.floor(Math.random() * 100) + 1}`;

            return {
                id,
                orderNo: id,
                memberName,
                amount,
                orderType: orderTypeOptions[typeIndex].value,
                orderTypeName: orderTypeOptions[typeIndex].label,
                paymentMethod: paymentMethodOptions[paymentIndex].value,
                paymentMethodName: paymentMethodOptions[paymentIndex].label,
                orderTime: orderTime.toLocaleString(),
                remark: Math.random() > 0.7 ? `备注信息${index + 1}` : ''
            };
        });

        pagination.total = 235; // 模拟总数据量

        // 加载完成后初始化图表
        loading.value = false;
        initCharts();
    }, 1000);
};

// 初始化图表
const initCharts = () => {
    // 延迟一下确保DOM已渲染
    setTimeout(() => {
        initIncomeChart();
        initPaymentChart();
        initTrendChart();

        // 窗口大小变化时重新渲染图表
        window.addEventListener('resize', () => {
            incomeChart?.resize();
            paymentChart?.resize();
            trendChart?.resize();
        });
    }, 100);
};

// 初始化收入来源饼图
const initIncomeChart = () => {
    const chartDom = document.getElementById('incomeChart');
    if (!chartDom) return;

    incomeChart = echarts.init(chartDom);
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'horizontal',
            bottom: 'bottom'
        },
        series: [
            {
                name: '收入来源',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: incomeStats.value
            }
        ]
    };

    incomeChart.setOption(option);
};

// 初始化支付方式饼图
const initPaymentChart = () => {
    const chartDom = document.getElementById('paymentChart');
    if (!chartDom) return;

    paymentChart = echarts.init(chartDom);
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'horizontal',
            bottom: 'bottom'
        },
        series: [
            {
                name: '支付方式',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: paymentStats.value
            }
        ]
    };

    paymentChart.setOption(option);
};

// 初始化收入趋势图
const initTrendChart = () => {
    const chartDom = document.getElementById('trendChart');
    if (!chartDom) return;

    trendChart = echarts.init(chartDom);

    let xAxisData = [];
    let incomeData = [];
    let expenseData = [];

    // 根据选择的时间维度生成不同的数据
    if (dataDimension.value === 'day') {
        xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        incomeData = [3200, 4500, 5000, 4200, 6500, 7800, 5500];
        expenseData = [1200, 900, 1500, 1300, 1200, 1500, 1100];
    } else if (dataDimension.value === 'week') {
        xAxisData = ['第一周', '第二周', '第三周', '第四周'];
        incomeData = [21000, 23500, 25000, 28000];
        expenseData = [6500, 7200, 8000, 7500];
    } else {
        xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        incomeData = [85000, 78000, 95000, 88000, 92000, 98000, 108000, 112000, 95000, 88000, 105000, 120000];
        expenseData = [25000, 23000, 28000, 24000, 26000, 27000, 30000, 32000, 28000, 26000, 32000, 35000];
    }

    const option = {
        title: {
            text: '收支趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['收入', '支出'],
            top: 'bottom'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '收入',
                type: 'bar',
                data: incomeData,
                itemStyle: {
                    color: '#67C23A'
                }
            },
            {
                name: '支出',
                type: 'bar',
                data: expenseData,
                itemStyle: {
                    color: '#F56C6C'
                }
            }
        ]
    };

    trendChart.setOption(option);
};

// 切换图表时间维度
const changeDimension = (dim) => {
    dataDimension.value = dim;
    initTrendChart();
};

// 处理页码变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page;
    loadData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.currentPage = 1;
    loadData();
};

// 处理查询
const handleSearch = () => {
    pagination.currentPage = 1;
    loadData();
};

// 重置查询条件
const resetSearch = () => {
    searchForm.keyword = '';
    searchForm.paymentMethod = '';
    searchForm.orderType = '';
    searchForm.dateRange = [];

    handleSearch();
};

// 导出财务报表
const exportFinanceReport = () => {
    ElMessage.success('财务报表导出成功');
};

// 导出收支明细
const exportDetailReport = () => {
    ElMessage.success('收支明细导出成功');
};

// 对账功能
const reconciliation = () => {
    ElMessage.info('打开对账页面');
};

// 初始化加载
onMounted(() => {
    loadData();
});
</script>

<template>
    <div class="finance-container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2>财务管理</h2>
            <div class="header-actions">
                <el-button type="primary" @click="exportFinanceReport">
                    <el-icon>
                        <Document />
                    </el-icon>
                    财务报表
                </el-button>
                <el-button type="success" @click="exportDetailReport">
                    <el-icon>
                        <Printer />
                    </el-icon>
                    导出明细
                </el-button>
                <el-button type="warning" @click="reconciliation">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    对账
                </el-button>
            </div>
        </div>

        <!-- 统计卡片 -->
        <el-row :gutter="20" v-loading="loading">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-card shadow="hover" class="stat-card">
                    <div class="stat-title">总收入</div>
                    <div class="stat-value income">¥{{ financeStats.totalIncome.toLocaleString() }}</div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-card shadow="hover" class="stat-card">
                    <div class="stat-title">总支出</div>
                    <div class="stat-value expense">¥{{ financeStats.totalExpense.toLocaleString() }}</div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-card shadow="hover" class="stat-card">
                    <div class="stat-title">净收入</div>
                    <div class="stat-value">¥{{ financeStats.balance.toLocaleString() }}</div>
                    <div class="stat-subtitle">利润率: {{ incomePercentage }}</div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
                <el-card shadow="hover" class="stat-card">
                    <div class="stat-title">今日收入</div>
                    <div class="stat-value">¥{{ financeStats.todayIncome.toLocaleString() }}</div>
                    <div class="stat-subtitle compare-up">较昨日: {{ financeStats.comparedYesterday }}</div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="chart-row" v-loading="loading">
            <el-col :xs="24" :lg="12">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>收入来源分布</span>
                        </div>
                    </template>
                    <div id="incomeChart" class="chart"></div>
                </el-card>
            </el-col>
            <el-col :xs="24" :lg="12">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>支付方式分布</span>
                        </div>
                    </template>
                    <div id="paymentChart" class="chart"></div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 收入趋势图 -->
        <el-card class="trend-chart-card" v-loading="loading">
            <template #header>
                <div class="card-header">
                    <span>收支趋势</span>
                    <div class="dimension-selector">
                        <el-radio-group v-model="dataDimension" size="small" @change="changeDimension">
                            <el-radio-button label="day">日维度</el-radio-button>
                            <el-radio-button label="week">周维度</el-radio-button>
                            <el-radio-button label="month">月维度</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
            </template>
            <div id="trendChart" class="trend-chart"></div>
        </el-card>

        <!-- 交易记录 -->
        <el-card class="order-card">
            <template #header>
                <div class="card-header">
                    <span>交易记录</span>
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 240px;" />
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :model="searchForm" inline class="search-form">
                <el-form-item label="关键词">
                    <el-input v-model="searchForm.keyword" placeholder="订单号/会员" clearable />
                </el-form-item>
                <el-form-item label="支付方式">
                    <el-select v-model="searchForm.paymentMethod" placeholder="全部" clearable>
                        <el-option v-for="item in paymentMethodOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="交易类型">
                    <el-select v-model="searchForm.orderType" placeholder="全部" clearable>
                        <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="orderList" v-loading="loading" border style="width: 100%">
                <el-table-column prop="orderNo" label="订单号" width="120" />
                <el-table-column prop="orderTypeName" label="交易类型" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.orderType === 'room' ? 'success' :
                                row.orderType === 'recharge' ? 'primary' :
                                    row.orderType === 'goods' ? 'warning' : 'info'
                            ">
                            {{ row.orderTypeName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="memberName" label="会员姓名" width="120" />
                <el-table-column prop="amount" label="金额" width="120">
                    <template #default="{ row }">
                        <span class="income">¥{{ row.amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="paymentMethodName" label="支付方式" width="120" />
                <el-table-column prop="orderTime" label="交易时间" width="180" />
                <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<style scoped>
.finance-container {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.stat-card {
    text-align: center;
    padding: 20px;
    margin-bottom: 20px;
    height: 100%;
}

.stat-title {
    font-size: 16px;
    color: #606266;
    margin-bottom: 15px;
}

.stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 5px;
}

.stat-subtitle {
    font-size: 14px;
    color: #909399;
}

.income {
    color: #67C23A;
}

.expense {
    color: #F56C6C;
}

.compare-up {
    color: #67C23A;
}

.compare-down {
    color: #F56C6C;
}

.chart-row {
    margin-bottom: 20px;
}

.chart-card,
.trend-chart-card,
.order-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chart {
    height: 300px;
}

.trend-chart {
    height: 400px;
}

.search-form {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>
